# -*- coding: utf-8 -*-

import sys
import os
sys.path.append("trunk")
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import wx
from widget import ToasterBox as TB
import wx.lib.hyperlink as hyperlink
from wx.lib.ticker import Ticker
import wx.lib.anchors as anchors
from datetime import datetime

from widget.wgtEventID import *
from widget.wgtMenu import *
from widget.wgtList import ListDemo
from widget.wgtStatusBar import StatusBarDemo
from widget.wgtSplitterWindow import SplitterWindowDemo
from utils.host import get_ip_address, get_hostname

from apps.models import Event as EventModel
if os.name != 'posix':
    import pyTTS

class TBox(wx.Frame):
    def _init_Timer(self):
        print 'init Timer Window'
        self.timer = wx.Timer(self)
        if os.name != 'posix':
            self.tts = pyTTS.Create()
            self.tts.SetVoiceByName('MSSimplifiedChineseVoice')        
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(1000)
    
    def _init_TaskBarIcon(self):
        # 创建系统托盘ICO对象并赋给tbicon
        self.tbicon = wx.TaskBarIcon()
        icon = wx.Icon('firebug.ico', wx.BITMAP_TYPE_ICO)
        self.tbicon.SetIcon(icon, '')
        # 右键单击任务栏处理方法
        wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarRightClick)
        wx.EVT_TASKBAR_LEFT_UP(self.tbicon, self.OnTaskBarRightClick)
   
    
    def _init_MenuBar(self):
        self.SetMenuBar(MenuBarDemo())
        self.Bind(wx.EVT_MENU, self.onExit, id=ID_EXIT)
        self.Bind(wx.EVT_MENU, self.onSet, id=ID_SET)
        self.Bind(wx.EVT_MENU, self.onAbout, id=ID_ABOUT)
        self.Bind(wx.EVT_MENU, self.onRunServer, id=ID_RUNSERVER)
    
    def _init_SplitterWindow(self):
        self.splitterwindow = SplitterWindowDemo(self.backgroundPanel)
        #sty = wx.BORDER_NONE
        #sty = wx.BORDER_SIMPLE
        sty = wx.BORDER_SUNKEN
        
        p1 = wx.Window(self.splitterwindow, style=sty)
        p1.SetBackgroundColour("pink")
        wx.StaticText(p1, -1, "Panel One", (5,5))
        
        p2 = wx.Window(self.splitterwindow, style=sty)
        p2.SetBackgroundColour("sky blue")
        wx.StaticText(p2, -1, "Panel Two", (5,5))
        
        self.splitterwindow.SetMinimumPaneSize(20)
        self.splitterwindow.SplitVertically(p1, p2, -100)
        
#        return self.splitterwindow
        
    def _init_StatusBar(self):
        self.statusBar1 = StatusBarDemo(self)
        self.SetStatusBar(self.statusBar1)
        
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"事件提醒Demo",
                 pos=wx.DefaultPosition, size=(800,600), name='frame1')
#        // 初始化Panel
        self.panel = wx.Panel(parent=self, size=(800, 600), 
                            id=-1, name='panel1', 
                            style=wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN
                            | wx.FULL_REPAINT_ON_RESIZE, 
                            pos=(0, 0))
        self.panel.SetBackgroundColour(wx.Color(255, 255, 0))
        self.panel.SetAutoLayout(True)
        self.backgroundPanel = wx.Panel(
                                size=(784, 584), parent=self.panel, 
                                id=-1, 
                                name='backgroundPanel', 
                                style=wx.SIMPLE_BORDER | wx.CLIP_CHILDREN,
#                                | wx.FULL_REPAINT_ON_RESIZE,
                                pos = (8, 8)
                                )
        
        self.backgroundPanel.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.backgroundPanel.SetConstraints(
            anchors.LayoutAnchors(self.backgroundPanel, True, True, True, True)
        )
#        self.anchoredPanel = wx.Panel(
#                                size=(88, 48), id=-1, 
#                                parent=self.backgroundPanel, name='anchoredPanel', 
#                                style=wx.SIMPLE_BORDER, pos=(104, 16)
#                                )
#        
#        self.anchoredPanel.SetBackgroundColour(wx.Colour(0, 0, 222))
#        self.anchoredPanel.SetConstraints(
#            anchors.LayoutAnchors(self.anchoredPanel, False, False, True, True)
#        )
        
        self._init_TaskBarIcon()
        self._init_MenuBar()
        self._init_StatusBar()
        self._init_Timer()
        # 重写窗体关闭事件
#        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        
        # 菜单-绑定事件
        
        self._init_SplitterWindow()
#        self.box = wx.BoxSizer(wx.VERTICAL)
#        self.subbox = wx.BoxSizer(wx.HORIZONTAL)
#        self.box.AddSizer(self.subbox)
#        self.box.Add(self.splitterwindow, 1, wx.GROW, 1)
#        panel.SetSizer(self.box)
#        panel.SetAutoLayout(True)
        # init ListBox
##        self.listBox = ListDemo(self.backgroundPanel)
##        self.listBox.SetConstraints(
##            anchors.LayoutAnchors(self.listBox, True, True, True, True)
##        )
##        self.btnOK = wx.Button(self.backgroundPanel, id=-1, label="btnOK",
##            pos=(100, 100), size=(50, 20), style=1, name='btnOK')
##        self.Bind(wx.EVT_BUTTON, self.onAbout, self.btnOK)
##        self.btnOK.SetConstraints(
##            anchors.LayoutAnchors(self.btnOK, False, False, True, True)
##        )
#        sizerV = wx.BoxSizer(wx.VERTICAL)
#        sizerV.Add(self.listBox, 1, wx.GROW)
##        self.box = wx.BoxSizer(wx.VERTICAL)
##        self.subbox = wx.BoxSizer(wx.HORIZONTAL)
##        self.box.AddSizer(self.subbox)
##        self.box.Add(self.btnOK, 1, flag=wx.EXPAND)  # , 1, wx.GROW, 1
##        self.panel.SetSizer(self.box)
##        self.panel.SetAutoLayout(True)
        
#        horSz = wx.BoxSizer(wx.HORIZONTAL)
#        runButton = wx.Button(panel, -1, "run TBox")
#        mainSz.Add((0, 3))
#        mainSz.Add(horSz, 1, wx.EXPAND | wx.BOTTOM, 7)
#        horSz.Add(runButton,1,0,1)
#        runButton.Bind(wx.EVT_BUTTON, self.run)
        
        # 初始化定时器Window
#        self.SetSize((800, 600))
        self.Center()
        self.Show()
    
    def run(self):
        tbstyle = TB.TB_COMPLEX
        windowstyle = TB.TB_CAPTION
        closingstyle = TB.TB_ONCLICK
        tb = TB.ToasterBox(self, tbstyle=tbstyle, windowstyle=windowstyle, closingstyle=closingstyle)
        tb.SetTitle("hello title")
        tb.SetPopupSize((200, 150))
        tb.SetPopupPosition((824, 586))
        tb.SetPopupPauseTime(30000)
        tb.SetPopupScrollSpeed(8)
        tbpanel = tb.GetToasterBoxWindow()
        panel = wx.Panel(tbpanel, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        horsizer1 = wx.BoxSizer(wx.HORIZONTAL)
        # 设置位图
        myimage = wx.Bitmap("andrea.jpeg", wx.BITMAP_TYPE_JPEG)#
        stbmp = wx.StaticBitmap(panel, -1, myimage)
        horsizer1.Add(stbmp, 0)
        # 设置文字
        strs = "This Is Another Example Of ToasterBox, A Complex One. This Kind Of"
        strs = strs + " ToasterBox Can Be Created Using The Style TB_COMPLEX."
        sttext = wx.StaticText(panel, -1, strs)
        sttext.SetFont(wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL, False, "Verdana"))
        horsizer1.Add(sttext, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
        # 设置链接
        hl = hyperlink.HyperLinkCtrl(panel, -1, "My Home Page",
                                     URL="http://xoomer.virgilio.it/infinity77/")
        
        sizer.Add((0,5))        
        sizer.Add(horsizer1, 0, wx.EXPAND) # sizer添加horizer1
        
        horsizer2 = wx.BoxSizer(wx.HORIZONTAL)
        horsizer2.Add((5, 0))
        horsizer2.Add(hl, 0, wx.EXPAND | wx.TOP, 10)
        sizer.Add(horsizer2, 0, wx.EXPAND) # sizer添加horizer2

        tk = Ticker(panel)
        tk.SetText("Hello From wxPython!")
        
        horsizer3 = wx.BoxSizer(wx.HORIZONTAL)
        horsizer3.Add((5, 0))
        horsizer3.Add(tk, 1, wx.EXPAND | wx.TOP, 10)
        horsizer3.Add((5,0))
        sizer.Add(horsizer3, 0, wx.EXPAND) # sizer添加horizer3
        
        sizer.Layout()
        panel.SetSizer(sizer)
        
        tb.AddPanel(panel)
        tb.Play()
    
    # 重写窗体关闭事件
#    def OnCloseWindow(self, evt):
#        self.Hide()
    
    # 右键单击任务栏处理方法
    def OnTaskBarRightClick(self, evt):
        print 'OnContextMenu'
        self.PopupMenu(PopupMenuDemo())
    
    def onAbout(self, evt):
        dlg = wx.MessageDialog(self, u'''
技术支持:
    开发语言： Python
    Web框架：  Django 1.0
    类库：     wxPython, pyTTS
    第三方库： ToasterBox
    数据库：   Sqlite3

开发目标： 实现对事件的文字提示和语音提醒

运行环境： Windows

                           作者:张鹏''', u'关于', wx.OK)
        dlg.ShowModal()
        dlg.Destroy()
        
        
    def onSet(self, evt):
        self.Show()
    
    def onExit(self, evt):
        self.Close(0)
    
    def onRunServer(self, evt):
        print 'onRunServer'
    
    def OnTimer(self, evt):
        now = datetime.now()
        self.statusBar1.SetStatusText(now.strftime("%Y-%m-%d %H:%M:%S"), 3)
        try:
            now = now.strptime(now.strftime("%Y-%m-%d-%H:%M:%S"), "%Y-%m-%d-%H:%M:%S")
            latest_event = EventModel.objects.filter(eventtime__gte=now).order_by("eventtime")[0]
            print "event time: %s" % latest_event.eventtime
            self.statusBar1.SetStatusText("event time: %s" % latest_event.eventtime, 2)
            print str(now.strftime("%Y-%m-%d-%H:%M:%S"))
            if str(now.strftime("%Y-%m-%d-%H:%M:%S")) == \
                str(latest_event.eventtime.strftime("%Y-%m-%d-%H:%M:%S")):
                print "the event %s will be platforms" % latest_event.eventtime
                wx.CallAfter(self.frame.run)
                if os.name != 'posix':
                    self.tts.Speak(latest_event.description)                
        except IndexError:
            print 'no events'
            self.statusBar1.SetStatusText("no events", 2)
    

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = TBox(None, -1)
#    frame.Show()
    app.MainLoop()